<?php
namespace app\admin\controller;

use app\common\model\AppointmentUpstart as AppointmentUpstartModel;
use app\common\model\HelpGetUpstart as HelpGetUpstartModel;

use app\common\component\help_to_upstart\HelpToUpstartService;

class AppointmentUpstart extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();

		$this -> checkAuthorization();
	}

	public function index() {
		$resultAppointmentUpstart = AppointmentUpstartModel::alias('a_r')
			-> join('league_user u', 'a_r.user_id = u.user_id')
			-> field(
				'a_r.help_appointment_upstart_id, a_r.user_id, a_r.appointment_price, a_r.remaining_price, a_r.create_time, a_r.begin_time, a_r.to_num, a_r.status, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			-> order('a_r.status ASC, a_r.begin_time ASC')
			-> paginate(10);
		$this -> view -> assign('appointmentUpstarts', $resultAppointmentUpstart);

		$this -> view -> assign('totalHelpGetUpstart', HelpGetUpstartModel::where('status', 0) -> count());

		return $this -> view -> fetch();
	}

	public function match() {
		$helpAppointmentUpstartId = $this -> request -> get('help_appointment_upstart_id', 0, 'int');

		$getAppointmentUpstart = AppointmentUpstartModel::get(['help_appointment_upstart_id' => $helpAppointmentUpstartId]);
		if(!$getAppointmentUpstart || $getAppointmentUpstart -> getData('status') != 0) {
			echo '<meta charset="utf-8"><script>alert("预约订单不存在或已经匹配完成!");window.location.href="/shuashuale/appointment/upstart";</script>';exit;
		}
		$this -> view -> assign('appointmentUpstart', $getAppointmentUpstart);

		if($getAppointmentUpstart -> remaining_price <= 0) {
			$getAppointmentUpstart -> status = 1;
			$getAppointmentUpstart -> begin_time = time();

			$getAppointmentUpstart -> save();
			echo '<meta charset="utf-8"><script>alert("预约订单金额为0!");window.location.href="/shuashuale/appointment/upstart";</script>';exit;
		}

		$helpGetUpstarts = HelpGetUpstartModel::alias('h_g_r')
			-> join('league_user u', 'h_g_r.user_id = u.user_id')
			-> field(
				'h_g_r.help_get_upstart_id, h_g_r.help_to_upstart_id, h_g_r.order_id, h_g_r.price, h_g_r.create_time, h_g_r.begin_time, h_g_r.status, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			-> where('h_g_r.status = 0 AND h_g_r.price <= ' . $getAppointmentUpstart -> remaining_price . ' AND h_g_r.user_id <> ' . $getAppointmentUpstart -> user_id)
			-> order('h_g_r.sort ASC, begin_time ASC')
			-> paginate(10, false, ['query' => ['help_appointment_upstart_id' => $helpAppointmentUpstartId]]);

		$this -> view -> assign('helpGetUpstarts', $helpGetUpstarts);

		return $this -> view -> fetch();
	}

	public function handleMatch() {
		$post = $this -> request -> post();
		if(!isset($post['help_get_upstart_ids'])) {
			echo '<meta charset="utf-8"><script>alert("无选择匹配订单!");window.location.href="/shuashuale/appointment/upstart";</script>';exit;
		}

		$getAppointmentUpstart = AppointmentUpstartModel::get(['help_appointment_upstart_id' => $post['help_appointment_upstart_id']]);
		if(!$getAppointmentUpstart || $getAppointmentUpstart -> getData('status') != 0) {
			echo '<meta charset="utf-8"><script>alert("预约订单不存在或已经匹配完成!");window.location.href="/shuashuale/appointment/upstart";</script>';exit;
		}

		$helpGetUpstartIdsStr = '';
		foreach($post['help_get_upstart_ids'] as $help_get_upstart_id) {
			$helpGetUpstartIdsStr .= $help_get_upstart_id . ',';
		}
		$helpGetUpstartIdsStr = rtrim($helpGetUpstartIdsStr, ',');

		$currentTime = time();

		$selectHelpGetUpstarts = HelpGetUpstartModel::where('help_get_upstart_id in(' . $helpGetUpstartIdsStr . ')') -> select();
		foreach($selectHelpGetUpstarts as $helpGetUpstart) {
			if(($getAppointmentUpstart -> remaining_price <= 0) || ($getAppointmentUpstart -> remaining_price < $helpGetUpstart -> price)) {
				echo '<meta charset="utf-8"><script>alert("订单匹配成功!");window.location.href="/shuashuale/appointment/upstart/match?help_appointment_upstart_id=' . $post['help_appointment_upstart_id'] . '";</script>';exit;
			}

			\think\Db::startTrans();
			try {
				$getAppointmentUpstart -> remaining_price -= $helpGetUpstart -> price;
				$getAppointmentUpstart -> begin_time = $currentTime;
				$getAppointmentUpstart -> to_num += 1;
				if($getAppointmentUpstart -> remaining_price <= 0) {
					$getAppointmentUpstart -> status = 1;
				}
				if(!$getAppointmentUpstart -> save()) {
					throw new \Exception('预约,个别订单匹配失败');
				}

				$resultHelpToUpstart = (new HelpToUpstartService()) -> create([
					'help_get_upstart_id' => $helpGetUpstart -> help_get_upstart_id,
					'user_id' => $getAppointmentUpstart -> user_id,
					'price' => $helpGetUpstart -> price,
					'create_time' => $currentTime,
					'begin_time' => $currentTime,
					'over_time' => $currentTime + getParam('HELP_TO_RICH_OVERTIME') * 60 * 60,
					'status' => 1
				]);
				if($resultHelpToUpstart['code'] != 0) {
					throw new \Exception('打款,个别订单匹配失败');
				}

				$helpGetUpstart -> status = 1;
				$helpGetUpstart -> begin_time = $currentTime;
				$helpGetUpstart -> help_to_upstart_id = $resultHelpToUpstart['data']['help_to_upstart'] -> help_to_upstart_id;
				if(!$helpGetUpstart -> save()) {
					throw new \Exception('提现,个别订单匹配失败');
				}
				\think\Db::commit();
			} catch(\Exception $e) {
				\think\Db::rollback();

				echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/shuashuale/appointment/upstart/match?help_appointment_upstart_id=' . $post['help_appointment_upstart_id'] . '";</script>';exit;
			}
		}

		echo '<meta charset="utf-8"><script>alert("订单匹配成功!");window.location.href="/shuashuale/appointment/upstart";</script>';exit;
	}
}
?>